// Copyright 2006 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.
package bcexchanger;

import java.io.IOException;
import java.util.Vector;
import javax.microedition.io.file.FileConnection;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import bcexchanger.comm.ExchangeListener;
import bcexchanger.comm.ExchangerComm;
import bcexchanger.comm.ExchangerCommImpl;
import bcexchanger.ui.AddressBookScreen;
import bcexchanger.ui.AlertMessage;
import bcexchanger.ui.FilesScreen;
import bcexchanger.ui.MainScreen;
import bcexchanger.ui.ProgressScreen;
import bcexchanger.ui.Screen;
import bcexchanger.ui.ServiceListScreen;
import co.edu.uniandes.contextMobileApp.mundo.ContextMobileApp;

/**
 * 
 * This is the main application class which extends MIDlet class. It
 * serves as a parent to UI states (package example.BCExchanger.ui)
 * and listens to communicational events by implementing
 * ExchangeListener interface
 * 
 * @see example.BCExchanger.comm.ExchangeListener
 */
public class BCExchangerMIDlet extends MIDlet
    implements ExchangeListener {

  private boolean commIsInitialized = false;
  private ExchangerComm comm;
  private int selectedServiceIndex;
  private MainScreen scr = new MainScreen(this);
  private FileConnection selectedFile;
  
  private ContextMobileApp mundo;
  
  /**
   * Constructor
   */
  public BCExchangerMIDlet() { 
      mundo = new ContextMobileApp(this);
  }

  /**
   * Changes the current UI screen
   * <p>
   * This method is used to display and make active a UI screen
   * 
   * @param screen -
   *          UI screen to display
   * @see example.BCExchanger.ui.Screen
   */
  public void changeScreen(Screen screen) {
    screen.makeActive();
  }

  /**
   * Called to force termination of MIDlet
   */
  public void quit() {
    if (comm != null) {
      comm.cancelWaiting();
    }

    try {
      destroyApp(true);
      notifyDestroyed();
    } catch (MIDletStateChangeException e) {
      // Ignore, we are closing anyways
    }
  }

  /**
   * Saves the index of the service of choice
   * <p>
   * This method is used in case several services are found during
   * service discovery In this case the ServiceListScreen is displayed
   * and on user selection this method is called to save the index of
   * the service of choice.
   * 
   * @param index -
   *          index of the serivice chosen by the user
   */
  public void serviceSelected(int index) {
    selectedServiceIndex = index;
  }

  /**
   * Intitializes the communication module
   */
  public void initComm() 
  {
    if (!commIsInitialized) { // avoid double initializing
      comm = new ExchangerCommImpl(this);
      commIsInitialized = true;
    }
  }

  /**
   * Getter method for Exchanger - class representing communication
   * module
   * 
   * @return a class implementing ExchangerComm interface,
   *         representing communication module
   */
  public ExchangerComm getExchanger() {
    return comm;
  }

  protected void destroyApp(boolean arg0)
      throws MIDletStateChangeException {}

  protected void startApp() throws MIDletStateChangeException {
    // ensure that we have own business card selected
   
    changeScreen(scr);
    
  }

  protected void pauseApp() {}

  public void onInquiryComplete(int code) {
    if (code == ExchangerComm.DONE) {
      String text = "Searching for Business Card Exchange service...";
      changeScreen(new ProgressScreen(this, text));
    } else if (code == ExchangerComm.ERROR) {
      changeScreen(new AlertMessage(this, "Errors during inquiry",
         scr));
    } else if (code == ExchangerComm.CANCELED) {
      changeScreen(new AlertMessage(this, "Inquiry is canceled",
          scr));
    } else {
      // unknwon error
      throw new RuntimeException("Internal error #26");
    }

  }

  public void onServiceDiscoveryComplete(int code) 
  {
    if (code == ExchangerComm.DONE) 
    {
      String text = "Sending own business card...";
      changeScreen(new ProgressScreen(this, text));
    }
    else if (code == ExchangerComm.NO_RECORDS) {
      changeScreen(new AlertMessage(
          this,
          "Cannot find Business card exchange service on the devices",
          scr));
    } else if (code == ExchangerComm.ERROR) {
      changeScreen(new AlertMessage(this,
          "Errors during service discovery", scr));
    } else if (code == ExchangerComm.CANCELED) {
      changeScreen(new AlertMessage(this,
          "Service discovery is canceled",scr));
    } else {
      // unknown error
      throw new RuntimeException("Internal error #27");
    }
  }

  public synchronized int resolveMultipleServices(Vector friendlyNames) throws InterruptedException {
    changeScreen(new ServiceListScreen(this, friendlyNames));

    wait(); // wait until the choise is made

    return selectedServiceIndex;

  }

  public byte[] getOwnBC() throws Exception {
    byte[] vCard = null;
    String uid;
    try {
      uid = Storage.getBCUID();
      vCard = AddressBook.getVCard(uid);
    } catch (Exception e) 
    {
      throw new Exception("getOwnBC did not succeed");
    }
    return vCard;
  }

  public void onSendComplete(int code) {

    if (code == ExchangerComm.DONE) {
      String text = "Send was successful!";
      changeScreen(new AlertMessage(this, text,
              scr));
    } else if (code == ExchangerComm.CANCELED) {
      changeScreen(new AlertMessage(this, "Send is canceled ",
          scr));
    } else { // error
    	
      changeScreen(new AlertMessage(this, "Errors during sending ",
    		 scr ));
    }
  }


  public void onReceiveComplete(int code) {
    if (code == ExchangerComm.DONE) {
      changeScreen(new AlertMessage(this, "Receiving was successful!",
          scr));    	
    } else if (code == ExchangerComm.CANCELED) {
      changeScreen(new AlertMessage(this, "Receiving is canceled ",
          scr));
    } else { // error
      changeScreen(new AlertMessage(this, "Errors during receiving ",
          scr));
    }
  }

  public void onReceiveBC(byte[] vCard) throws Exception {
   AddressBook.setVCard(vCard);
  }

  /**
   * This is a helper methods which unblocks waiting code in
   * resolveMultipleServices()
   */
  public synchronized void unblock() {
    notify(); // let resolveMultipleServices complete
  }

  public void onGetComplete(int code) {

  }

  public void onPutComplete(int code) {

  }

  /**
   * Called in case of problems with Bluetooth OBEX server accepting connection
   * 
   */
  public void onServerError() {
    changeScreen(new AlertMessage(this,
    "Fatal Bluetooth error. Application will exit"));
    return;
  }

    public void setSelectedFile(FileConnection selectedFile) 
    {
       this.selectedFile = selectedFile;
    }
    
    public FileConnection getSelectedFile() 
    {
       return selectedFile;
    }

    public void agregarArchivo() {
        mundo.agregarArchivo(getSelectedFile());
    }
    
  

    public Vector darMisArchivos() {
        return mundo.getArchivos();
    }

    public String darInfoArchivo(String string) 
    {
        try {
            return mundo.getInfoArchivo(string);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

}
